<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/constanttype' }">常数类别管理</el-breadcrumb-item>
      <el-breadcrumb-item>常数项管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="15">
        <el-col :span="10">
          <el-input placeholder="请输入内容" clearable v-model="queryInfo.query">
            <!-- 当点击搜索的时候调用方法getUserList查询数据 -->
            <el-button slot="append" icon="el-icon-search" @click="getConstantItemList()"></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <!-- 添加按钮 -->
          <el-button
            type="primary"
            icon="el-icon-circle-plus-outline"
            circle
            @click="dialogFormVisible = true"
          ></el-button>
          <!-- 批量删除按钮 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="deleteall()"
            v-show="multipleSelection!=null&&multipleSelection!=''"
          ></el-button>
           <!-- 返回按钮 -->
          <el-button
            el-button type="warning" icon="el-icon-refresh-left" circle
            @click="toType()"
          ></el-button>
          <el-dialog title="新增常数项" :visible.sync="dialogFormVisible" :before-close="handleClose">
            <el-form :model="addForm" ref="addForm">
              <el-form-item label="所属常数类别" :label-width="formLabelWidth" prop="constanttypeid">
                <template>
                  <el-select v-model="addForm.constanttypeid" clearable placeholder="请选择所属常数类别">
                    <el-option
                      v-for="item in constanttypelist"
                      :key="item.id"
                      :label="item.constanttypename"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </template>
              </el-form-item>
              <el-form-item label="常数项编码" :label-width="formLabelWidth" prop="constantcode">
                <el-input v-model="addForm.constantcode" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="常数项名称" :label-width="formLabelWidth" prop="constantname">
                <el-input v-model="addForm.constantname" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click=" dialogFormVisible = false;resetForm('addForm')">取 消</el-button>
              <el-button type="primary" @click="add()">确 定</el-button>
            </div>
          </el-dialog>
        </el-col>
        
      </el-row>
    </el-card>

    <el-table
      :data="tableData"
      style="width: 100%"
      border
      stripe
      :row-key="getRowKey"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
      <el-table-column label="编号" width="50px" type="index" align="center"></el-table-column>
      <el-table-column prop="constantType.constanttypename" label="所属常数类别" align="center"></el-table-column>
      <el-table-column prop="constantcode" label="常数项编码" align="center"></el-table-column>
      <el-table-column prop="constantname" label="常数项名称" align="center"></el-table-column>

      <!-- <el-table-column
                label="状态">
      <template slot-scope="scope">-->
      <!-- scope.row 代表这一行数据 -->
      <!-- scope.row.mg_state 绑定当前行的数据 -->
      <!-- <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
                </template>
      </el-table-column>-->

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <!-- slot-scope="scope" -->
          <!-- 修改按钮 -->

          <el-button
            type="primary"
            icon="el-icon-setting"
            size="mini"
            @click="dialogFormVisiblee=true;getConstantItemById(scope.row.id)"
          >修改</el-button>

          <!-- 删除按钮  scope.row.id-->
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteitem(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <el-dialog title="修改常数项" :visible.sync="dialogFormVisiblee" :before-close="handleClose">
      <el-form :model="updateForm" ref="addForm">
        <el-form-item label="所属常数类别" :label-width="formLabelWidth" prop="constanttypeid">
          <template>
            <el-select v-model="updateForm.constanttypeid" clearable placeholder="请选择所属常数类别">
              <el-option
                v-for="item in constanttypelist"
                :key="item.id"
                :label="item.constanttypename"
                :value="item.id"
              ></el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="常数项编码" :label-width="formLabelWidth" prop="constantcode">
          <el-input v-model="updateForm.constantcode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="常数项名称" :label-width="formLabelWidth" prop="constantname">
          <el-input v-model="updateForm.constantname" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click=" dialogFormVisiblee = false;resetForm('addForm')">取 消</el-button>
        <el-button type="primary" @click="update()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      multipleSelection: [],
      queryInfo: {
        //查询条件
        query: "",
        id: this.$route.query.id,
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5,
      },
      total: 0,

      tableData: [],
      updateForm: {},
      constanttypeid: "",
      addForm: {
        constanttypeid: "",
        constantcode: "",
        constantname: "",
      },
      constanttypelist: [],
      // 控制添加用户对话框的显示与隐藏
      dialogTableVisible: false,
      dialogFormVisiblee: false,
      dialogFormVisible: false,
      formLabelWidth: "120px",
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
    };
  },

  created() {
    this.getConstantType();
    this.getConstantItemList();
  },

  methods: {
    // 指定一个key标识这一行的数据
    getRowKey(row) {
      return row.id;
    },

    // val表示选中的表格行数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(this.multipleSelection)
    },
    deleteall() {
      let list = [];
      for (let i in this.multipleSelection) {
        list[i] = this.multipleSelection[i].id;
      }
      console.log(list);
       this.$confirm("此操作将执行批量删除, 是否继续?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const {
            data: res,
          } = await this.$http.put("constantitemcontroller/deleteall", {
            list,
          });
          if (res.meta.status !== 200) {
            return this.$message.error("删除用户失败！");
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
           this.getConstantItemList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getConstantItemList();
    },

    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage;
      this.getConstantItemList();
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          this.resetForm("addForm");
        })
        .catch((_) => {});
    },
    /**
     * 重置表单
     */
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    /**
     * 通过id获取常数类别
     */
    async getConstantItemById(id) {
      const {
        data: res,
      } = await this.$http.get("constantitemcontroller/getconstantitem", {
        params: { id: id },
      });
      this.updateForm = res.data;
      console.log(res.data);
    },
    /**
     * 获取下拉列表
     */
    async getConstantType() {
      const { data: res } = await this.$http.get(
        "constanttypecontroller/getlist"
      );
      this.constanttypelist = res.data;
      // console.log(this.tableData)
    },
    /**
     * 获取页面信息
     */
    async getConstantItemList() {
      const { data: res } = await this.$http.post(
        "constantitemcontroller/getconstantitemlist",
        this.queryInfo
      );
      this.tableData = res.data;
      console.log(res.data);
      this.total = res.totalpage;
    },
    /**
     *添加
     */
    add() {
      this.$confirm("是否添加?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (
            this.addForm.constantcode == null ||
            this.addForm.constanttypecode == ""
          ) {
            return this.$message.error("添加失败请输入正确的常数项编码");
          }
          if (
            this.addForm.constantname == null ||
            this.addForm.constanttypename == ""
          ) {
            return this.$message.error("添加失败请输入正确的常数项名称");
          }
          const { data: res } = await this.$http.post(
            "constantitemcontroller/insert",
            this.addForm
          );
          //正常情况下axios会返回一个promise对象，这个对象是比较复杂的，所以为了简化操作
          //需要在向服务器发送异步请求之前加一个await，那么这个await是需要与async结合使用的
          //所以需在validate中加入一个async，这样从后台返回的就不是一个promise对象了。

          this.$message({
            type: "success",
            message: "添加成功!",
          });
          this.resetForm("addForm");
          this.dialogFormVisible = false;

          this.getConstantItemList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消添加",
          });
        });
    },

    /**
     * 删除
     */
    deleteitem(id) {
      this.$confirm("此操作将执行删除操作, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const {
            data: res,
          } = await this.$http.put("constantitemcontroller/delete", { id });
          if (res.meta.status !== 200) {
            return this.$message.error("删除用户失败！");
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getConstantItemList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /**
     * 修改
     */
    update(id) {
      this.$confirm("是否确认修改?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.put(
            "constantitemcontroller/update",
            this.updateForm
          );
          // console.log(res)
          if (res.meta.status != 200) {
            return this.$message.error("修改信息失败！");
          }
          this.dialogFormVisiblee = false;
          this.$message({
            type: "success",
            message: "修改成功!",
          });
          this.getConstantItemList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消修改",
          });
        });
    },
    toType(){
      this.$router.push({
        path: "/constanttype",
      });
    }
  },
};
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 20px;
}

.el-form-item {
  text-align: left;
}
</style>